﻿using System;
using Epm.AppLogic.Framework;
using msBsc.Xsd.DataTds;
using System.Data;

namespace msBsc.AppLogic.DataAlc
{
    public class CBizShpScoreTradingLog : CustBizObject
    {
        private CDmShpScoreTradingLog m_CDmShpScoreTradingLog = new CDmShpScoreTradingLog();
        private CDmShpScoreTradingLog oDmShpScoreTradingLog
        {
            get { return m_CDmShpScoreTradingLog; }
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        public CBizShpScoreTradingLog()
            : base()
        {
            this.DataObj = new CDbAccess();
            this.DataObj.Init(this.m_CDmShpScoreTradingLog.SHP_SCORE_TRADING_LOG);
            this.TableName = this.DataObj.TableName;
            this.DataObj.KeyField = this.DataObj.Fields["SCORE_TRADING_ID"]; 
        }

        /// <summary>
        /// 新增记录前的处理
        /// </summary>
        /// <param name="drw">新增数据行</param>
        /// <returns>true/false</returns>
        /// <remarks>
        /// 生成ID值
        /// </remarks>
        protected override bool BeforeRowAdded(DataRow drw)
        {
            if (drw[this.KeyFieldName].ToString().Length < 10)
            {
                drw[this.KeyFieldName] = this.DataObj.NewID();
            }
            if (drw["TRADING_NO"].ToString() == string.Empty)
            {
                drw["TRADING_NO"] = GetNewTradingNo();// msBsc.SvRef.ApplicationConst.Const.GetNewSerialNo("TRADING_NO", System.DateTime.Now.Year.ToString(), 8);
            }
            //drw["BUYER_DEL"] = false;
            //drw["BUYER_RATE_SID"] = "";

            return true;
        }
        public string GetNewTradingNo()
        {
            return "01" + msBsc.SvRef.ApplicationConst.Const.GeneratelongId().ToString();
        }

        /// <summary>
        /// 记录修改前检验
        /// </summary>
        /// <param name="drw">当前记录</param>
        /// <returns>>校验合法，返回值为true,否则返回false</returns>
        /// <remarks>
        /// ID不允许修改,并把此修改操作记录到BSE_MODIFY_HISTORY表中
        /// </remarks>
        protected override bool BeforeRowModified(DataRow drw)
        {
            //ID不容许修改
            if (drw[this.KeyFieldName].ToString() != drw[this.KeyFieldName, DataRowVersion.Original].ToString())
            {
                Exception e = new Exception(this.TableName + "表的主键" + this.KeyFieldName + "字段不允许被修改");
                throw e;
            } 
            return true;
        }

        protected override bool AfterRowModified(DataRow drw)
        { 
            return true;
        }

        public DataSet SelectByIds(string strIdS)
        {
            DataSet ds = this.DataObj.QueryBySQL("SELECT * FROM " + this.TableName + " WHERE  " + this.KeyFieldName + " IN  ('" + strIdS.Replace("'", "").Replace(",", "','") + "')");
            ds.Tables[0].TableName = this.TableName;
            return ds;
        }

        public DataSet SelectByAccountNo(string strAccountNo)
        {
            DataSet ds = this.DataObj.QueryBySQL("SELECT * FROM " + this.TableName + " WHERE ACCOUNT_NO='" + strAccountNo + "' ORDER BY INITIAL_DT ASC");
            ds.Tables[0].TableName = this.TableName;
            return ds;
        }

        public DataSet SelectForFinder(string strTRADING_NO, string strUSER_NME, string strCOMM_USER_NME)
        {
            if (strUSER_NME != string.Empty || strCOMM_USER_NME != string.Empty)
            {
                strCOMM_USER_NME = "";
            }
            if (strCOMM_USER_NME != string.Empty)
            {
                DataSet ds1 = this.DataObj.QueryBySQL("SELECT * FROM SHP_COMMERCIAL_TENANT_INFO WHERE COMM_TENANT_NME='" + strCOMM_USER_NME + "' OR USER_NME='" + strCOMM_USER_NME + "'");
                if (ds1.Tables[0].Rows.Count > 0)
                {
                    strCOMM_USER_NME = ds1.Tables[0].Rows[0]["COMM_TENANT_ID"].ToString();
                }
            }


            DataSet ds = this.DataObj.QueryBySQL("SELECT * FROM " + this.TableName + " WHERE (1=1)"
                + (strTRADING_NO == string.Empty ? "" : " AND (TRADING_NO='" + strTRADING_NO + "')")
                + (strUSER_NME == string.Empty ? "" : " AND (ACCOUNT_NO='" + strUSER_NME + "')")
                + (strCOMM_USER_NME == string.Empty ? "" : " AND (ACCOUNT_NO='" + strCOMM_USER_NME + "')")
                + "  ORDER BY INITIAL_DT ASC");
            ds.Tables[0].TableName = this.TableName;
            return ds;
        }

        /// <summary>
        /// 交易完成后赠送积分
        /// </summary>
        /// <param name="drOrder"></param>
        public void AddTradingLogForCmpOrder(DataRow drOrder)
        {
            if ((int)drOrder["RCV_SCORE_QTY"] <= 0)
            {
                return;
            }
            //            DataSet dsLis = this.DataObj.QueryBySQL(@"
            //    SELECT 
            //    A.USER_NME
            //    ,A.COMM_TENANT_ID
            //    ,A.COMM_TENANT_NME
            //    ,A.ORDER_FORM_ID
            //    ,A.ORDER_FORM_NO 
            //    ,TRADING_QTY=SUM(ISNULL(B.GOODS_STRIKE_SCORE,0)*B.GOODS_QTY)
            //    ,TRADING_AMT=SUM((B.GOODS_STRIKE_PRICE*B.GOODS_QTY)-ISNULL(B.DISCOUNT_AMT,0.00))  
            //    FROM SHP_ORDER_FORM A 
            //    LEFT OUTER JOIN SHP_ORDER_FORM_LIST B ON A.ORDER_FORM_ID=B.ORDER_FORM_ID 
            //    WHERE
            //    A.ORDER_FORM_ID IN('" + strOrderId.Replace(",", "','") + @"')
            //    GROUP BY 
            //    A.USER_NME
            //    ,A.COMM_TENANT_ID
            //    ,A.COMM_TENANT_NME
            //    ,A.ORDER_FORM_ID
            //    ,A.ORDER_FORM_NO 
            //    ");
            //using (msBsc.AppLogic.DataAlc.CBizShpScoreTradingLog objrad = new CBizShpScoreTradingLog())
            //{ 
            DataSet dstrad = new CDmShpScoreTradingLog();
            //for (int i = 0; i < dsLis.Tables[0].Rows.Count; i++)
            //{
            //店铺台帐减少积分
            //DataRow drlist = dsLis.Tables[0].Rows[i];
            DataRow drnewtrad = dstrad.Tables[0].NewRow();
            drnewtrad["SCORE_TRADING_ID"] = this.DataObj.NewID();
            drnewtrad["ACCOUNT_NO"] = drOrder["COMM_TENANT_ID"];
            drnewtrad["ACCOUNT_NME"] = drOrder["COMM_TENANT_NME"];
            drnewtrad["USER_TYPE_CID"] = "1";
            drnewtrad["PAY_DIR"] = "支出";//收付：收入、支出
            drnewtrad["TRADING_SID"] = "已支付"; 
            drnewtrad["TRADING_NO"] = drOrder["ORDER_FORM_NO"];
            drnewtrad["TRADING_NME"] = drOrder["ORDER_FORM_NME"];// msBsc.SvRef.ApplicationConst.Const.GetNewSerialNo("TRADING_NO", System.DateTime.Now.Year.ToString(), 8);
            drnewtrad["TRADING_TYPE_CID"] = "赠予";//赠予，获赠，购买，消费，收取
            drnewtrad["OTH_ACCOUNT_NO"] = drOrder["USER_NME"];
            drnewtrad["OTH_ACCOUNT_NME"] = drOrder["USER_NME"];
            drnewtrad["TRADING_QTY"] = -(int)drOrder["RCV_SCORE_QTY"];
            drnewtrad["TRADING_PRICE"] = msBsc.SvRef.SysConst.decScoreUsePrice();
            drnewtrad["TRADING_AMT"] = -(int)drOrder["RCV_SCORE_QTY"] * msBsc.SvRef.SysConst.decScoreUsePrice();
            drnewtrad["ORDER_FORM_ID"] = drOrder["ORDER_FORM_ID"];
            drnewtrad["ORDER_FORM_NO"] = drOrder["ORDER_FORM_NO"];
            drnewtrad["TRADING_DESC"] = "销售商品赠送积分";
            dstrad.Tables[0].Rows.Add(drnewtrad);

            //客户增加积分
            DataRow drnewtrad2 = dstrad.Tables[0].NewRow();
            drnewtrad2["SCORE_TRADING_ID"] = this.DataObj.NewID();
            drnewtrad2["ACCOUNT_NO"] = drOrder["USER_NME"];
            drnewtrad2["ACCOUNT_NME"] = drOrder["USER_NME"];
            drnewtrad2["USER_TYPE_CID"] = "2";
            drnewtrad2["PAY_DIR"] = "收入";//收付：收入、支出
            drnewtrad2["TRADING_SID"] = "已支付"; 
            drnewtrad2["TRADING_NO"] = drOrder["ORDER_FORM_NO"];
            drnewtrad2["TRADING_NME"] = drOrder["ORDER_FORM_NME"];
            drnewtrad2["TRADING_TYPE_CID"] = "获赠";//赠予，获赠，购买，消费，收取
            drnewtrad2["OTH_ACCOUNT_NO"] = drOrder["COMM_TENANT_ID"];
            drnewtrad2["OTH_ACCOUNT_NME"] = drOrder["COMM_TENANT_NME"];
            drnewtrad2["TRADING_QTY"] = (int)drOrder["RCV_SCORE_QTY"];
            drnewtrad2["TRADING_PRICE"] = msBsc.SvRef.SysConst.decScoreUsePrice();
            drnewtrad2["TRADING_AMT"] = (int)drOrder["RCV_SCORE_QTY"] * msBsc.SvRef.SysConst.decScoreUsePrice();
            drnewtrad2["ORDER_FORM_ID"] = drOrder["ORDER_FORM_ID"];
            drnewtrad2["ORDER_FORM_NO"] = drOrder["ORDER_FORM_NO"];
            drnewtrad2["TRADING_DESC"] = "购买商品获赠积分";
            dstrad.Tables[0].Rows.Add(drnewtrad2);

            this.Update(dstrad);
            this.DataObj.ExecuteBySQL("UPDATE A SET SCORE_QTY=ISNULL(A.SCORE_QTY,0)+" + drOrder["RCV_SCORE_QTY"].ToString() + " FROM SHP_CUSTOMER_INFO A WHERE A.USER_NME='" + drOrder["USER_NME"].ToString() + "'");
            this.DataObj.ExecuteBySQL("UPDATE A SET SCORE_QTY=ISNULL(A.SCORE_QTY,0)-" + drOrder["RCV_SCORE_QTY"].ToString() + " FROM SHP_COMMERCIAL_TENANT_INFO A WHERE A.COMM_TENANT_ID='" + drOrder["COMM_TENANT_ID"].ToString() + "'");
            //}



            ////推广系统增加积分
            //using (msBsc.AppLogic.DataAlc.CBizShpPromotionScoreLog oinf = new msBsc.AppLogic.DataAlc.CBizShpPromotionScoreLog())
            //{
            //    DataSet dstm2=this.DataObj.QueryBySQL("SELECT B.FWDUSER_NME,A.PROMOTION_NME FROM SYS_USER A LEFT OUTER JOIN SYS_USER B ON A.PROMOTION_NME IS NOT NULL AND A.PROMOTION_NME<>'' AND A.PROMOTION_NME=B.USER_NME WHERE A.PROMOTION_NME IS NOT NULL AND A.PROMOTION_NME<>'' AND A.USER_NME='"+drOrder["USER_NME"].ToString()+"'");
            //    if (dstm2.Tables[0].Rows.Count > 0)
            //    {
            //        oinf.AddFromScoreLog(drnewtrad2, drOrder["USER_NME"].ToString(), dstm2.Tables[0].Rows[0]["PROMOTION_NME"].ToString(), dstm2.Tables[0].Rows[0]["FWDUSER_NME"].ToString());
            //    }
            //}
            //}
        }

        /// <summary>
        /// 商家获赠或购买积分
        /// </summary>
        /// <param name="drw"></param>
        public void AddTradingLogFromScoreSalse(DataRow drw)
        {
            //店铺台帐增加记录 
            DataSet dstrad = new CDmShpScoreTradingLog();
            DataRow drnewtrad = dstrad.Tables[0].NewRow();
            drnewtrad["SCORE_TRADING_ID"] = this.DataObj.NewID();
            drnewtrad["ACCOUNT_NO"] = drw["COMM_TENANT_ID"];
            drnewtrad["ACCOUNT_NME"] = drw["COMM_TENANT_NME"];
            drnewtrad["USER_TYPE_CID"] = "1";
            drnewtrad["PAY_DIR"] = "收入";//收付：收入、支出
            drnewtrad["TRADING_SID"] = "已支付"; 
            drnewtrad["TRADING_NO"] = drw["TRADING_NO"];
            if (drw["SALES_TYPE_CID"].ToString() == "赠予")
            {
                drnewtrad["TRADING_NME"] = "获赠积分";
                drnewtrad["TRADING_TYPE_CID"] = "获赠";//赠予，获赠，购买，消费，
            }
            else
            {
                drnewtrad["TRADING_NME"] = "购买积分";
                drnewtrad["TRADING_TYPE_CID"] = "购买";//赠予，获赠，购买，消费，
            }
            drnewtrad["OTH_ACCOUNT_NO"] = "system";
            drnewtrad["OTH_ACCOUNT_NME"] = "地接客商城";
            drnewtrad["TRADING_QTY"] = drw["SALES_QTY"];
            drnewtrad["TRADING_PRICE"] = (decimal)drw["STL_AMT"] / (int)drw["SALES_QTY"];
            drnewtrad["TRADING_AMT"] = drw["STL_AMT"];
            drnewtrad["ORDER_FORM_ID"] = "";
            drnewtrad["ORDER_FORM_NO"] = "";
            drnewtrad["TRADING_DESC"] = "";
            dstrad.Tables[0].Rows.Add(drnewtrad);
            this.Update(dstrad);
            this.DataObj.ExecuteBySQL("UPDATE A SET SCORE_QTY=ISNULL(A.SCORE_QTY,0)+" + drw["SALES_QTY"].ToString() + " FROM SHP_COMMERCIAL_TENANT_INFO A WHERE A.COMM_TENANT_ID='" + drw["COMM_TENANT_ID"].ToString() + "'");
        }

        /// <summary>
        /// 积分购买商品
        /// </summary>
        /// <param name="drOrder"></param>
        public void AddTradingLogForAddOrder(DataRow drOrder)
        {
            if ((int)drOrder["PAID_SCORE_QTY"] <= 0)
            {
                return;
            } 
            DataSet dstrad = new CDmShpScoreTradingLog();
            //for (int i = 0; i < dsLis.Tables[0].Rows.Count; i++)
            //{
            //店铺台帐增加积分
            //DataRow drlist = dsLis.Tables[0].Rows[i];
            DataRow drnewtrad = dstrad.Tables[0].NewRow();
            drnewtrad["SCORE_TRADING_ID"] = this.DataObj.NewID();
            drnewtrad["ACCOUNT_NO"] = drOrder["COMM_TENANT_ID"];
            drnewtrad["ACCOUNT_NME"] = drOrder["COMM_TENANT_NME"];
            drnewtrad["USER_TYPE_CID"] = "1";
            drnewtrad["PAY_DIR"] = "收入";//收付：收入、支出
            drnewtrad["TRADING_SID"] = "已支付"; 
            drnewtrad["TRADING_NO"] = drOrder["ORDER_FORM_NO"];
            drnewtrad["TRADING_NME"] = drOrder["ORDER_FORM_NME"];//msBsc.SvRef.ApplicationConst.Const.GetNewSerialNo("TRADING_NO", System.DateTime.Now.Year.ToString(), 8);
            drnewtrad["TRADING_TYPE_CID"] = "收取";//赠予，获赠，购买，消费，收取
            drnewtrad["OTH_ACCOUNT_NO"] = drOrder["USER_NME"];
            drnewtrad["OTH_ACCOUNT_NME"] = drOrder["USER_NME"];
            drnewtrad["TRADING_QTY"] = (int)drOrder["PAID_SCORE_QTY"];
            drnewtrad["TRADING_PRICE"] = msBsc.SvRef.SysConst.decScoreUsePrice();
            drnewtrad["TRADING_AMT"] = (int)drOrder["PAID_SCORE_QTY"] * msBsc.SvRef.SysConst.decScoreUsePrice();
            drnewtrad["ORDER_FORM_ID"] = drOrder["ORDER_FORM_ID"];
            drnewtrad["ORDER_FORM_NO"] = drOrder["ORDER_FORM_NO"];
            drnewtrad["TRADING_DESC"] = "积分商城销售商品收取积分";
            dstrad.Tables[0].Rows.Add(drnewtrad);

            //客户减少积分
            DataRow drnewtrad2 = dstrad.Tables[0].NewRow();
            drnewtrad2["SCORE_TRADING_ID"] = this.DataObj.NewID();
            drnewtrad2["ACCOUNT_NO"] = drOrder["USER_NME"];
            drnewtrad2["ACCOUNT_NME"] = drOrder["USER_NME"];
            drnewtrad2["USER_TYPE_CID"] = "2";
            drnewtrad2["PAY_DIR"] = "支出";//收付：收入、支出
            drnewtrad2["TRADING_SID"] = "已支付"; 
            drnewtrad2["TRADING_NO"] = drOrder["ORDER_FORM_NO"];
            drnewtrad2["TRADING_NME"] = drOrder["ORDER_FORM_NME"];
            drnewtrad2["TRADING_TYPE_CID"] = "消费";//赠予，获赠，购买，消费，收取
            drnewtrad2["OTH_ACCOUNT_NO"] = drOrder["COMM_TENANT_ID"];
            drnewtrad2["OTH_ACCOUNT_NME"] = drOrder["COMM_TENANT_NME"];
            drnewtrad2["TRADING_QTY"] = -(int)drOrder["PAID_SCORE_QTY"];
            drnewtrad2["TRADING_PRICE"] = msBsc.SvRef.SysConst.decScoreUsePrice();
            drnewtrad2["TRADING_AMT"] = -(int)drOrder["PAID_SCORE_QTY"] * msBsc.SvRef.SysConst.decScoreUsePrice();
            drnewtrad2["ORDER_FORM_ID"] = drOrder["ORDER_FORM_ID"];
            drnewtrad2["ORDER_FORM_NO"] = drOrder["ORDER_FORM_NO"];
            drnewtrad2["TRADING_DESC"] = "购买商品消费积分";
            dstrad.Tables[0].Rows.Add(drnewtrad2);

            this.Update(dstrad);
            this.DataObj.ExecuteBySQL("UPDATE A SET SCORE_QTY=ISNULL(A.SCORE_QTY,0)-" + drOrder["PAID_SCORE_QTY"].ToString() + " FROM SHP_CUSTOMER_INFO A WHERE A.USER_NME='" + drOrder["USER_NME"].ToString() + "'");
            this.DataObj.ExecuteBySQL("UPDATE A SET SCORE_QTY=ISNULL(A.SCORE_QTY,0)+" + drOrder["PAID_SCORE_QTY"].ToString() + " FROM SHP_COMMERCIAL_TENANT_INFO A WHERE A.COMM_TENANT_ID='" + drOrder["COMM_TENANT_ID"].ToString() + "'");
            //}


            //}
        }


        /// <summary>
        /// 商家制作积分卡
        /// </summary>
        /// <param name="drw"></param>
        public void CreatScoreCardForShop(DataRow drw)
        {
            //店铺台帐减少记录 
            DataSet dstrad = new CDmShpScoreTradingLog();
            DataRow drnewtrad = dstrad.Tables[0].NewRow();
            drnewtrad["SCORE_TRADING_ID"] = this.DataObj.NewID();
            drnewtrad["ACCOUNT_NO"] = drw["CREATE_ACCOUNT_NO"];
            drnewtrad["ACCOUNT_NME"] = drw["CREATE_ACCOUNT_NME"];
            drnewtrad["PAY_DIR"] = "支出";//收付：收入、支出
            drnewtrad["USER_TYPE_CID"] = "1";
            drnewtrad["TRADING_SID"] = "已支付";
            drnewtrad["TRADING_NME"] = "制作积分卡";
            drnewtrad["TRADING_NO"] = drw["SCORE_CARD_NO"];
            drnewtrad["TRADING_TYPE_CID"] = "制卡";//赠予，获赠，购买，消费， 充值，制卡，收取
            drnewtrad["OTH_ACCOUNT_NO"] = "system";
            drnewtrad["OTH_ACCOUNT_NME"] = "地接客商城";
            drnewtrad["TRADING_QTY"] = drw["SCORE_QTY"];
            drnewtrad["TRADING_PRICE"] = msBsc.SvRef.SysConst.decScoreSalesPrice();
            drnewtrad["TRADING_AMT"] = (int)drw["SCORE_QTY"] * msBsc.SvRef.SysConst.decScoreSalesPrice();
            drnewtrad["ORDER_FORM_ID"] = "";
            drnewtrad["ORDER_FORM_NO"] = "";
            drnewtrad["TRADING_DESC"] = "";
            dstrad.Tables[0].Rows.Add(drnewtrad);
            this.Update(dstrad);
            this.DataObj.ExecuteBySQL("UPDATE A SET SCORE_QTY=ISNULL(A.SCORE_QTY,0)-" + drw["SCORE_QTY"].ToString() + " FROM SHP_COMMERCIAL_TENANT_INFO A WHERE A.COMM_TENANT_ID='" + drw["CREATE_ACCOUNT_NO"].ToString() + "'");
        }


        /// <summary>
        /// 用户充值积分卡
        /// </summary>
        /// <param name="drw"></param>
        public void UseScoreCardForUser(DataRow drw)
        {
            //用户台帐增加记录 
            DataSet dstrad = new CDmShpScoreTradingLog();
            DataRow drnewtrad = dstrad.Tables[0].NewRow();
            drnewtrad["SCORE_TRADING_ID"] = this.DataObj.NewID();
            drnewtrad["ACCOUNT_NO"] = drw["USE_ACCOUNT_NO"];
            drnewtrad["ACCOUNT_NME"] = drw["USE_ACCOUNT_NME"];
            drnewtrad["PAY_DIR"] = "收入";//收付：收入、支出
            drnewtrad["USER_TYPE_CID"] = "2";
            drnewtrad["TRADING_SID"] = "已支付";
            drnewtrad["TRADING_NME"] = "充值积分卡";
            drnewtrad["TRADING_NO"] = drw["SCORE_CARD_NO"];
            drnewtrad["TRADING_TYPE_CID"] = "充值";//赠予，获赠，购买，消费， 充值，制卡
            drnewtrad["OTH_ACCOUNT_NO"] = "system";
            drnewtrad["OTH_ACCOUNT_NME"] = "地接客商城";
            drnewtrad["TRADING_QTY"] = drw["SCORE_QTY"];
            drnewtrad["TRADING_PRICE"] = msBsc.SvRef.SysConst.decScoreSalesPrice();
            drnewtrad["TRADING_AMT"] = (int)drw["SCORE_QTY"] * msBsc.SvRef.SysConst.decScoreSalesPrice();
            drnewtrad["ORDER_FORM_ID"] = "";
            drnewtrad["ORDER_FORM_NO"] = "";
            drnewtrad["TRADING_DESC"] = "";
            dstrad.Tables[0].Rows.Add(drnewtrad);
            this.Update(dstrad);
            this.DataObj.ExecuteBySQL("UPDATE A SET SCORE_QTY=ISNULL(A.SCORE_QTY,0)+" + drw["SCORE_QTY"].ToString() + " FROM SHP_CUSTOMER_INFO A WHERE A.USER_NME='" + drw["USE_ACCOUNT_NO"].ToString() + "'"); 
        }

    }
}
